package com.liqin.nothing.service.impl;

import com.liqin.nothing.service.SseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

/**
 * @author gonghl
 * @since 2024/7/18 上午 10:57
 */
@Service
@Slf4j
public class SseServiceImpl implements SseService {

    private static final Map<String, SseEmitter> CACHE = new ConcurrentHashMap<>();

    @Override
    public SseEmitter connect(String id) {
        // 设置超时时间，0表示不过期。默认30秒，超过时间未完成会抛出异常：AsyncRequestTimeoutException
        SseEmitter sseEmitter = new SseEmitter(0L);
        // 完成回调
        sseEmitter.onCompletion(completionCallBack(id));
        // 失败回调
        sseEmitter.onError(errorCallBack(id));
        // 超时回调
        sseEmitter.onTimeout(timeoutCallBack(id));
        CACHE.put(id, sseEmitter);
        log.info("创建新的sse连接{}", id);
        return sseEmitter;
    }

    @Override
    public boolean disconnect(String id) {
        SseEmitter emitter = CACHE.get(id);
        if (emitter != null) {
            emitter.complete();
            CACHE.remove(id);
            log.info("关闭sse连接{}", id);
        }
        return true;
    }

    @Override
    public boolean sendPrivate(String id, String msg) {
        SseEmitter emitter = CACHE.get(id);
        if (emitter != null) {
            try {
                emitter.send(msg);
                return true;
            } catch (IOException e) {
                log.error("消息发送失败", e);
            }
        }
        return false;
    }

    @Override
    public boolean sendGroup(String msg) {
        CACHE.keySet().forEach(id -> sendPrivate(id, msg));
        return true;
    }


    private Runnable completionCallBack(String id) {
        return () -> {
            log.info("结束连接：{}", id);
            disconnect(id);
        };
    }

    private Runnable timeoutCallBack(String id) {
        return () -> {
            log.info("连接超时：{}", id);
            disconnect(id);
        };
    }

    private Consumer<Throwable> errorCallBack(String id) {
        return throwable -> {
            log.info("连接异常：{}, e==>{}", id, throwable.getMessage());
            disconnect(id);
        };
    }

}
